package com.atguigu.gmall.consumer;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * 消息的消费者
 */
@Component
@Log4j2
public class Consumer {

    /**
     * 消费者消费者队列
     * @param channel
     * @param message
     */
    @RabbitListener(queues = "java_queue")
    public void receive(Channel channel , Message message) throws Exception{
        MessageProperties messageProperties = message.getMessageProperties();
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            //获取消息的属性消息
            byte[] body = message.getBody();
            String msg = new String(body, "utf-8");
            System.out.println("收到的消息内容"+ msg);
            //消息编号--offset
            System.out.println("消息的编号为"+deliveryTag);
//        //确认消息
            channel.basicAck(deliveryTag,false);

        }catch (Exception e){
            log.info(JSONObject.toJSONString(message));
            log.error(e.getMessage());
        }finally {

            if (messageProperties.getRedelivered()){
                //将消息进行记录--日志--数据库
                log.info(JSONObject.toJSONString(message));
                //拒绝消息
                channel.basicReject(deliveryTag,false);
                return;
            }
            //放回队列，重新消费一次
            channel.basicReject(deliveryTag,true);
        }
    }
}
